<template>
  <div class="userAdd">
    <el-dialog
      v-dialog-drag
      v-bind="$attrs"
      :visible.sync="showDialog" v-on="$listeners" @open="onOpen" @close="onClose" title=""
      :close-on-click-modal="false">
      <el-tabs v-model="activeName" @tab-click="handleClick" style="width:75%; max-height: 500px" >
        <el-tab-pane label="角色信息" name="first" :class="{'abc1':isOverflow1}">
          <el-row :gutter="15">
            <el-form ref="elForm" :model="upRoleVO" :rules="rules" size="medium" label-width="100px">
              <el-col :span="12">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="upRoleVO.roleName" placeholder="请输入角色名"  :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
                <el-form-item label="角色详情" prop="remark">
                  <el-input v-model="upRoleVO.remark" placeholder="请输入角色详情"  :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
                <el-form-item label="创建时间" prop="createTime">
                  <el-date-picker v-model="upRoleVO.createTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                  :style="{width: '100%'}" placeholder="请选择创建时间" clearable></el-date-picker>
                </el-form-item>
                <el-form-item label="是否禁用" prop="status">
                  <el-input v-model="upRoleVO.status" placeholder="请输入手机号" clearable
                            :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="角色菜单" name="second" :class="{'abc':isOverflow1}">
          <el-tree
            :data="menusdata"
            show-checkbox
            node-key="id"
            @check="checkMenuChange"
            :default-expanded-keys="checkedKeysMenu"
            :default-checked-keys="checkedKeysMenu"
            :props="defaultProps">
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="角色交易" name="third" :class="{'abc':isOverflow1}">
          <el-input style="height: 50px; width: 200px"
            placeholder="请输入交易名称"
            prefix-icon="el-icon-search"
            v-model="inputPermissionName"
            @input="findPermissionsInput">
          </el-input>
          <el-tree
            @check="checkPermissionChange"
            :data="permissionsdata"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2, 3]"
            :default-checked-keys="checkedKeysPermission"
            :props="defaultProps1">
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="角色权限" name="fourth">
          <el-button round icon="el-icon-plus" @click="addUser" >新增</el-button>
          <el-divider></el-divider>
          <el-table
            ref="multipleTable"
            tooltip-effect="dark"
            :data="userListData"
            border
            style="width: 100%"
            max-height="400px"
            @selection-change="handleSelectionChange"
          >
              <el-table-column
                id=""
                type="selection"
                prop="id"
                label="全选"
                width="50">
              </el-table-column>
              <el-table-column
                label="用户id"
                width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.isSet">
                      <el-input size="mini" v-model="scope.row.id"></el-input>
                    </span>
                    <span v-else>{{ scope.row.id}}</span>
                  </template>
              </el-table-column>
              <el-table-column
                label="用户名称"
                width="210">
                <template slot-scope="scope">
                    <span v-if="scope.row.isSet">
                      <el-autocomplete
                        size="mini"
                        v-model="scope.row.username"
                        @select="handleSelect"
                        clearable
                        placeholder="请输入用户名"
                        :fetch-suggestions="querySearchAsync"
                      ></el-autocomplete>
                    </span>
                  <span v-else>{{ scope.row.username}}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="scope">
                  <el-button size="mini"
                             type="primary"
                             round
                             plain
                             v-if="scope.row.isSet"
                             @click="saveChange(scope.row)">保存</el-button>
                  <el-button type="danger" size="mini" round icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
                </template>
              </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="saveRMPUs">确定</el-button>
      </div>
      <AddUserSmail
        :userAddVisible="userAddVisible"
        @changeShow="disAddUserView"
      ></AddUserSmail>
    </el-dialog>
  </div>
</template>
<script>
import AddUserSmail from '@/views/users/AddUserSmail'
import  ImageCropper from '../../components/ImageCropper'
import  PanThumb from '../../components/PanThumb'
import {deleteImage} from '@/api/image'
import {saveUser } from '@/api/users'
import {findPermissionsByName} from '@/api/menu'
import {findUsers} from '@/api/users'
import {findUserByRoleId} from '@/api/role'
import {findUserByName} from '@/api/users'
import {UpdataRMPUss} from '@/api/role'

export default {
  inheritAttrs: false,
  components: {
    ImageCropper,
    PanThumb,
    AddUserSmail
  },
  props: {
    updateVisible:{
      type : Boolean,
      default:false
    },
    updateRoleVO:{
      type : Object,
      default :{}
    },
    menus:{
      type:Array,
      default:[]
    },
    permissions:{
      type:Array,
      default:[]
    },
    ownMunuIds:{
      type:Array,
      default:[]
    },
    ownPermissionIds:{
      type:Array,
      default:[]
    },
    userList:{
      type:Array,
      default:[]
    }
  },
  data() {
    return {
      saveRMPUVO:Object,
      userVO:{},
      userAddVisible:false,
      multipleSelection:[],
      userListData:[],
      isOverflow:false,
      isOverflow1:true,
      inputPermissionName:'',
      checkedKeysMenu:[],
      checkedKeysPermission:[],
      showDialog: false,
      activeName: 'first',
      upRoleVO: {
        id: null,
        roleName: null,
        remark: '',
        createTime: undefined,
        status: undefined,
      },
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      image: 'http://xinguan-parent11.oss-cn-beijing.aliyuncs.com/2021/04/10/dc1926488e7e45ada4b9b0ac02643c9a.png',
      rules: {
        roleName: [{
          // required: true,
          message: '请输入角色名',
          trigger: 'blur'
        }],
        remark: [{
          // required: true,
          message: '请输入角色详情',
          trigger: 'change'
        }],
        createTime: [{
          // required: true,
          message: '选择角色创建时间',
          trigger: 'blur'
        }],
        status: [{
          // required: true,
          message: '角色状态',
          trigger: 'blur'
        }],
      },
      menusdata: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1',
          children: [{
            id: 9,
            label: '三级 1-1-1'
          }, {
            id: 10,
            label: '三级 1-1-2'
          }]
        }]
      }, {
        id: 2,
        label: '一级 2',
        children: [{
          id: 5,
          label: '二级 2-1'
        }, {
          id: 6,
          label: '二级 2-2'
        }]
      }, {
        id: 3,
        label: '一级 3',
        children: [{
          id: 7,
          label: '二级 3-1'
        }, {
          id: 8,
          label: '二级 3-2'
        }]
      }],
      permissionsdata:[{id:1,menuName:"sdf"},{id:2,menuName:"sdff"}],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      defaultProps1: {
        children: 'children',
        label: 'menuName'
      },
    }
  },
  computed: {

  },
  watch: {
    updateVisible:function(){
      this.showDialog = this.updateVisible
    },
    updateRoleVO:function(){
      //监听updateUserVO改变
      this.upRoleVO.id = this.updateRoleVO.id
      this.upRoleVO.roleName = this.updateRoleVO.roleName
      this.upRoleVO.remark = this.updateRoleVO.remark
      this.upRoleVO.status = this.updateRoleVO.status
      let momentObj = this.moment(this.updateRoleVO.createTime, 'YYYY-MM-DD HH:MM:SS');
      let momentString = momentObj.format('YYYY-MM-DD');
      this.upRoleVO.createTime = momentString
    },
    menus:function (){
      this.menusdata = this.menus
    },
    permissions:function (){
      this.permissionsdata = this.permissions
    },
    ownMunuIds:function (){
      this.checkedKeysMenu = this.ownMunuIds
    },
    ownPermissionIds:function (){
      this.checkedKeysPermission = this.ownPermissionIds
    },
    userList:function (){
      this.userListData = this.userList
    },

  },
  created() {
  },
  mounted() {
  },
  methods: {
    checkMenuChange(a,b){
      this.checkedKeysMenu=b.checkedKeys
    },
    checkPermissionChange(a,b){
      this.checkedKeysPermission=b.checkedKeys
    },
    querySearchAsync(queryString, cb) {
      let username = ''
      let datas = []
      if(queryString != null && queryString != ''){
        username = queryString
      }
      findUsers(username).then(res=>{
        let datass = res.data.data
        if(datass != null && datass.length >0){
          datass.map((item)=>{
            datas.push({
              "value":item.username,
              "id":item.id
            })
          })
        }
        cb(datas)
      })

    },
    handleSelect(item) {
      console.log(item);
    },
    inputUserName(){

    },
    saveChange(val){
      if(val.username == null || val.username == ''){
        const h = this.$createElement;
        this.$notify({
          title: '请选择一条数据',
          message: h('i', { style: 'color: red' }, '请添加一个用户')
        });
      }
      findUserByRoleId(this.upRoleVO.id).then(res=>{
        if(res.data.data != null && res.data.data.length > 0){
          res.data.data.map((item)=>{
            if(item.username == val.username){
              const h = this.$createElement;
              this.$notify({
                title: '请选择一条数据',
                message: h('i', { style: 'color: red' }, '该用户已经拥有此角色')
              });
            }
          })
        }
      })
      //根据用户名查询用户id
      findUserByName(val.username).then(res=>{
        this.userVO = res.data.data
        if(this.userListData != null && this.userListData.length > 0) {
          this.userListData.map((item) => {
            if (item.username == val.username) {
              item.id = this.userVO.id
              item.isSet = false
            }
          })
        }
      })
    },
    addUser(){
      let myData =[]
      let row = {
        id: '',
        username: '',
        isSet: true
      }
      myData.push(row)
      this.userListData.map((item =>{
        item.isSet = true
        myData.push(item)
      }))
      this.userListData = myData
    },
    disAddUserView(data){
      if(data === 'false'){
        this.userAddVisible =false
      }else{
        this.userAddVisible =true
      }
    },
    deleteUser(userId){
      this.userListData.some((item, i)=>{
        if(item.id == userId){
          this.userListData.splice(i, 1)
          //在数组的some方法中，如果return true，就会立即终止这个数组的后续循环
          return true
        }
      })
    },
    handleSelectionChange(val) {
      console.log("handleSelectionChange")
      this.multipleSelection = val;
    },
    findPermissionsInput(){
      findPermissionsByName(this.inputPermissionName).then(res=>{
        this.permissionsdata=res.data.data
      })
    },
    handleChange(value, direction, movedKeys) {
      //可以通过direction回调right/left 来进行操作，right：把数字移到右边，left把数据移到左边
      if(direction === "right") {
      }
      if(direction === "left") {
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    onOpen() {},
    onClose() {
      this.$refs['elForm'].resetFields()
      console.log("onClose");
      this.$emit('changeShow','false')
      this.$emit('closeEdit','false')
      this.roleId=''
      this.upRoleVO={}
      // this.menusdata=[]
      // this.permissionsdata=[]
      // this.checkedKeys=[]
      // this.checkedKeys1=[]
    },
    close() {
      console.log("Close");
      // this.$emit('update:visible', false)
      this.$emit('changeShow','false')
      this.$emit('closeEdit','false')
      this.roleId=''
      this.upRoleVO={}
      // this.menusdata=[]
      // this.permissionsdata=[]
      // this.checkedKeys=[]
      // this.checkedKeys1=[]
    },
    saveRMPUs() {
      this.userListData.map((item=>{
        if(item.id == null || item.id == ""){
          this.$message.error('请先保存用户')
        }
      }))
      //调用保存  角色对应的角色信息 菜单 交易 用户
      this.saveRMPUVO = {
        upRoleVO : this.upRoleVO,
        ownMunuIds : this.checkedKeysMenu,
        ownPermissionIds : this.checkedKeysPermission,
        userListData : this.userListData
      }
      console.log(this.saveRMPUVO)
      UpdataRMPUss(this.saveRMPUVO).then(res=>{
        if(res.data.code == 200){
          this.$emit('changeShow','false')
          this.upUserVO = {}
          this.$notify.success({
            title:'操作成功',
            message:'角色信息操作成功'
          })
        }else{
          return this.$message.error('角色信息操作失败:')
        }
      })
    },
    async assUser(){
      const {data : res} = await saveUser(this.upUserVO);
      if(res.code == 200){
        this.$emit('changeShow','false')
        this.upUserVO = {}
        this.$notify.success({
          title:'操作成功',
          message:'用户操作成功'
        })
      }else{
        return this.$message.error('用户操作失败:'+ res.msg)
      }
    },
    field101BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    //弹窗后触发
    handleClose(){
      //子组件调用父组件方法，并传递参数
      this.$emit('changeShow','false')
    },
    // 上传成功后的回调函数
    cropSuccess (data) {
      let oldImage = this.image;
      //使用该属性保存上传之前的图片
      this.imagecropperShow = false
      this.upUserVO.avatar = this.image = data.msg
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1
      //上传头像成功后  删除之前的头像
      this.deleteAvater(oldImage)
    },
    // 关闭上传组件
    closeImage () {
      this.imagecropperShow = false
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1
    },
    async deleteAvater(oldImage){
      const {data} = await deleteImage(oldImage)
    },
    parentClick(a){
      //根据点击的用户名称  查询用户拥有的角色
    }
  }
}

</script>
<style lang = "less" scoped>
.el-upload__tip {
  line-height: 1.2;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 500px;
  display: block;
}
.el-dialog__body{
  height: 450px;
  width: 700px;
}
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}
//.el-tab-pane{
//  height: 400px;
//  overflow-y: scroll;
//}
.abc{
  height: 400px;
  overflow-y: scroll;
}
.abc1{
  width: 500px;
}
.el-divider{
  margin: 5px;

}
</style>
